<?php

class DatabaseController extends AppController {

	public $name = 'database';
	
	function beforeFilter() {
	    parent::beforeFilter(); 
		$this->C_auth->autoRedirect = false; //For override login
	    $this->C_auth->allowedActions = array('save','recover');

	}
	
	public function save() {
        $operation = Request::get_args('operation');
		$DbConfig = 'default';    		
	    $dbo =& ConnectionManager::getDataSource($DbConfig);
		$DbPrefix = $dbo->config['prefix'];	
        if($operation=='savebackup'){
		
	        $tabledb = Request::get_args('tabledb');
	        if(!$tabledb){	 
		        echo "<script language='javascript'> ShowMessageBox('至少要选择一项','-1'); </script>";
		        exit;				
	        }
	        if(!is_array($tabledb)){
		        $tabledb = str_replace('\"','"',$tabledb);
		        $tabledb	= unserialize($tabledb);
	        }

	        $sizelimit	= Request::get_args('sizelimit');
	        $start		= intval(Request::get_args('start'));
	        $step		= intval(Request::get_args('step'));
	        $tableid	= intval(Request::get_args('tableid'));
	        $dataid		= Request::get_args('dataid');
	        $data_num	= Request::get_args('data_num');
	        $aaa		= Request::get_args('aaa');
	        $k			= Request::get_args('k');


		    Loader::import('lib.ctime');
		    $ctime = new ctime();
	        $time_long=$ctime->long_time();
	        $time_custom=$ctime->custom('m_d_H_i');
	        $bak="/* Pspframework_Mall Backup SQL File \n Version: 1.0 \n Time: ".$time_long."\n Pspframework_Mall: http://www.pspframework.com*/\n\n\n\n";
	        
			$this->sizelimit = $sizelimit;
	        $this->tableid = $tableid;
	        $this->dataid = $dataid;
	        $this->data_num = $data_num;
	        $this->k = $k;	
			$this->stop=0;
	        $writedata=$this->bakupdata($dbo,$tabledb,$start);
			
	        if($aaa==""){
		        $aaa=num_rand(6);
	        }
	        $filedir='psp_'.$time_custom.'_'.$aaa;

	        $filename=$step.'.sql';
	        $step++;

	        trim($writedata) && writefile($filedir,$filename,$bak.$writedata,true,'ab');

	        if($this->stop==1){
		        $tabledb=serialize($tabledb);

		        echo "<script language='javascript'>location.href='".Router::url('admin/database/save/')."?operation=savebackup&start=".$start."&step=".$step."&tableid=".$tableid."&tabledb=".$tabledb."&dataid=".$dataid."&sizelimit=".$sizelimit."&data_num=".$data_num."&aaa=".$aaa."&k=".$k."';</script>";
		        exit;
	        }
	        /** 添加log */
	        $admin_log ="备份数据库";//"备份数据库";

	        echo "<script language='javascript'> ShowMessageBox('备份成功！','".Router::url('admin/database/recover/')."');</script>";
	        exit;
        }else{
 	        $step=1;
	        $start=0;
	        $tabledb=mysql_query("show table status from ".$dbo->config['database'].";");
	        while($row[]=mysql_fetch_array($tabledb)); 
			$this->set('row',$row);
        }	
		$this->set('start',$start);
		$this->set('step',$step);
	}	

	public function scandir($dir='') {	
        $dh  = opendir($dir);
        while (false !== ($filename = readdir($dh))) {
            $files[] = $filename;
        }
        return $files;	
	}
	
	public function recover() {

        $filedb=array();
        $files = $this->scandir(APP_ROOT.'/docs');
        $i=0;
        $file_array=array();
        foreach($files as $key=>$val){
	        if(substr($val,0,4)=='psp_'){
		        $file_array[$i][0]=$val;
		        $file = $this->scandir(APP_ROOT.'/docs/'.$val);
				
		        foreach($file as $item=>$na){
			        if($item>=2){
				        $strlen=16;
				        $fp=fopen(APP_ROOT."/docs/$val/$na",'rb');
				        $bakinfo=fread($fp,129);
				        fclose($fp);
				        $detail=explode("\n",$bakinfo);
				        $bk['name']=$na;
				        $bk['version']=substr($detail[1],10);
				        $bk['time']=substr($detail[2],7);
				        $bk['pre']=substr($na,0,$strlen);
				        $bk['num']=substr($na,$strlen,strrpos($na,'.')-$strlen);

				        $bk['MB'] = round((filesize(APP_ROOT.'/docs/'.$val.'/'.$na))/1024*100)/100;
				        $bk['MB'] = ($bk['MB']>1024) ? (round($bk['MB']/1024*100)/100).'M' : $bk['MB'].'K';
				        $filedb[$i][]=$bk;
			        }
		        }
		        $i++;
	        }
        }
		$DbConfig = 'default';    		
	    $dbo =& ConnectionManager::getDataSource($DbConfig);
		$DbPrefix = $dbo->config['prefix'];	
        //导入备份文件
        $operation	= Request::get_args('operation');
        if($operation=='bakin'){
		
	        $pre=Request::get_args('pre');
	        $dir=APP_ROOT.'/docs/'.$pre;
	        $file = $this->scandir($dir);
            
	        foreach($file as $key=>$val){
		        if($key>=2){
			        $key=$key-1;
			       // echo $d=$dir.'/'.$key.'.sql';
			        $this->bakindata($dbo,$dir.'/'.$key.'.sql');
					exit;
		        }
	        }

	        echo "<script language='javascript'> ShowMessageBox('导入成功！','".Router::url('admin/database/save/')."');  </script>";
        }

        //删除备份文件
        $fid=Request::get_args('fid');
        if($fid){
	        $dir=APP_ROOT.'/docs/'.$fid;
	        $dp = opendir($dir);
	        if ($dp !=false) {
		        while (false !== ($file1=readdir($dp))) {
			        if($file1!='.' && $file1!='..'){
				        unlink($dir.'/'.$file1);
			        }
		        }
		        closedir($dp);
		        rmdir($dir);
	        }
			header('Content-Type: text/html; charset='.Param::read('App.encoding'));
	        exit("删除成功！");
        }
        $this->set('file_array',$file_array);
        $this->set('filedb',$filedb);		
	}

	public function bakindata($dbo,$filename) {
	    ini_set('max_execution_time','0');
	    $sql=file($filename);
	    $query='';
	    $num=0;
	    foreach($sql as $key => $value){
		    $value=trim($value);
		    if(preg_match("/\;$/i",$value)){
			    $query.=$value;
				echo '['.$query.']<br/><br/><br/><br/>';
			    $dbo->fetchAll($query);
			    $query='';
		    } else{
			    $query.=$value;
		    }
	    }
    }	

	public function bakupdata($dbo,$tabledb,$start=0){
		$sizelimit = $this->sizelimit;
		$tableid = $this->tableid;
		$dataid = $this->dataid;
		$data_num = $this->data_num;
		$k = $this->k;
		$tableid=$tableid?$tableid:0;
		$dataid=$dataid?$dataid:0;
		$data_num=$data_num?$data_num:0;
		$k=$k?$k:0;
		$this->stop=0;
		$t_count=count($tabledb);
		$bakupdata="";

		for($i=$tableid;$i<$t_count;$i++){

			if($dataid>=$data_num){
				$dataid=0;
				$k=0;
				$bakupdata.= "DROP TABLE IF EXISTS $tabledb[$i];\n";
				$CreatTable = mysql_fetch_array(mysql_query("SHOW CREATE TABLE $tabledb[$i]"));
				$bakupdata.=$CreatTable['Create Table'].";\n\n";
			}

			$sql="SELECT * FROM $tabledb[$i]";
			$result_1=mysql_query($sql) or die('false getRs, Sql:'.$sql);
			$rs=array();
			while($rsRow=mysql_fetch_array($result_1)) {
				$rs[]=$rsRow;
			}		
			$data_num=count($rs);

			foreach($rs as $key=>$val){
				if($key>=$dataid){
					$num_F = count($val)/2;
					$k++;
					$table=$tabledb[$i];
					$bakupdata .= "INSERT INTO $table VALUES("."'".addslashes($val[0])."'";
					$tempdb='';
					for($j=1;$j<$num_F;$j++){
						$tempdb.=",'".str_replace("\n",'\n',addslashes($val[$j]))."'";
					}
					$bakupdata .=$tempdb. ");\n";

					if($sizelimit && strlen($bakupdata)>$sizelimit*1000){
						$this->stop=1;
						break;
					}
				}
			}

			$bakupdata .="\n";
			if($sizelimit && strlen($bakupdata)>$sizelimit*1000){
				$this->stop=1;
				break;
			}
			$tableid=$t_count;
			$dataid=$data_num;
		}

		if($this->stop==1){
			$tableid=$i;
			$dataid=$k;
		}
		return $bakupdata;
    }


	
}


function writefile($filedir,$filename,$data,$check=1,$method="rb+",$iflock=1,$chmod=1){
	if(!file_exists($filedir)){
		@mkdir(APP_ROOT.'/docs/'.$filedir);
	}
	$filename=APP_ROOT.'/docs/'.$filedir.'/'.$filename;
	$check && strpos($filename,'..')!==false;
	touch($filename);
	$handle=fopen($filename,$method);
	if($iflock){
		flock($handle,LOCK_EX);
	}
	fwrite($handle,$data);
	if($method=="rb+") ftruncate($handle,strlen($data));
	fclose($handle);
	$chmod && @chmod($filename,0777);
}
function num_rand($lenth){
	mt_srand((double)microtime() * 1000000);
	$randval="";
	for($i=0;$i<$lenth;$i++){
		$randval.= mt_rand(0,9);
	}
	$randval=substr(md5($randval),mt_rand(0,32-$lenth),$lenth);
	return $randval;
}
function delfile($filename,$check=1){
	@chmod ($filename, 0777);
	return @unlink($filename);
}

?> 